import decimal
import time

# Create your models here.
from django.db import models
from django.core.validators import MinValueValidator
from Dify.models.other import FaKuyouSuppliers


# 采购订单
class FaKuyouGoodsPurchaseOrder(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('1', '购货'),
        ('2', '退货'),
    ]

    STATUS_CHOICES = [
        ('0', '未入库'),
        ('1', '全部入库'),
        ('2', '部分入库'),
        ('3', '已取消'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    supplyer_code = models.CharField(max_length=30, null=True, blank=True, verbose_name='供应商编号')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    preferential_rate = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                            validators=[MinValueValidator(0)], verbose_name='优惠率')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                    validators=[MinValueValidator(0)], verbose_name='税额')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='0', verbose_name='状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    store_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                       validators=[MinValueValidator(0)], verbose_name='入库数量')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    note = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                  verbose_name='本次欠款')
    all_arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='总欠款')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=int(time.time()))
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=int(time.time()))

    class Meta:
        db_table = 'fa_kuyou_goods_purchase_order'
        verbose_name = '购货订单'
        verbose_name_plural = '购货订单'

    def __str__(self):
        return f"{self.purchase_code or '无编号'}-{self.get_purchase_type_display()}"


# 采购订单详情单
class FaKuyouGoodsPurchaseOrderInfo(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('1', '购货'),
        ('2', '退货'),
    ]

    STATUS_CHOICES = [
        ('0', '未入库'),
        ('1', '全部入库'),
        ('2', '部分入库'),
        ('3', '已取消'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    supplyer_code = models.CharField(max_length=30, null=True, blank=True, verbose_name='供应商编号')
    goods_code = models.CharField(max_length=30, default='', verbose_name='商品编号')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品备注')
    goods_attr = models.IntegerField(null=True, blank=True, verbose_name='商品属性ID')
    goods_unit = models.IntegerField(null=True, blank=True, verbose_name='商品单位ID')
    stores_id = models.IntegerField(null=True, blank=True, verbose_name='仓库ID')
    allow_stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='可用库存')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    purchase_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='可生成购货单数量')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='基本单位ID')
    basic_nmber = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='基本数量')
    unit_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='购货单价')
    tax_included = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                       validators=[MinValueValidator(0)], verbose_name='含税单价')
    discount = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                   verbose_name='折扣率')
    dis_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='折扣额')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    tax_rate = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                   verbose_name='税率')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                          validators=[MinValueValidator(0)], verbose_name='价税合计')
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    preferential_rate = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                            validators=[MinValueValidator(0)], verbose_name='优惠率')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='0', verbose_name='状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    library_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='未入库数量')
    library_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                        validators=[MinValueValidator(0)], verbose_name='未入库金额')
    library_time = models.IntegerField(null=True, blank=True, verbose_name='最后入库时间')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=time.time())
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=time.time())

    class Meta:
        db_table = 'fa_kuyou_goods_purchase_order_info'
        verbose_name = '购货订单详情'
        verbose_name_plural = '购货订单详情'


    def __str__(self):
        return f"{self.purchase_code or '无编号'}-{self.goods_code}"


# 采购单
class FaKuyouGoodsPurchase(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('1', '购货'),
        ('2', '退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未付款'),
        ('1', '全部付款'),
        ('2', '部分付款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    supplyer_code = models.CharField(max_length=30, null=True, blank=True, verbose_name='供应商编号')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    all_money = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='购货金额')
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货订单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    preferential_rate = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='优惠率(%)')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                    validators=[MinValueValidator(0)], verbose_name='税额')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='付款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    note = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                  verbose_name='本次欠款')
    all_arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='总欠款')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    cost_data = models.TextField(null=True, blank=True, verbose_name='采购费用明细')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=time.time())
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=time.time())

    class Meta:
        db_table = 'fa_kuyou_goods_purchase'
        verbose_name = '购货单'
        verbose_name_plural = '购货单'

    def save(self, *args, **kwargs):
        if self.pay_money < self.real_money:
            self.pay_status = '2'
        elif self.pay_money == self.real_money:
            self.pay_status = '1'
        else:
            self.pay_status = '0'

        # 计算欠款
        self.arrears = self.real_money - self.pay_money
        # 更新总欠款（供应商表中记录）
        supplier = FaKuyouSuppliers.objects.filter(supplyer_code=self.supplyer_code).first()
        self.all_arrears = supplier.need_give_account + supplier.receive_account + float(self.arrears)
        supplier.save()

        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.purchase_code or '无编号'}-{self.get_purchase_type_display()}"


# 采购详情单
class FaKuyouGoodsPurchaseInfo(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('1', '购货'),
        ('2', '退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未付款'),
        ('1', '部分付款'),
        ('2', '全部付款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='1', verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    supplyer_code = models.CharField(max_length=30, null=True, blank=True, verbose_name='供应商编号')
    goods_code = models.CharField(max_length=30, default='', verbose_name='商品编号')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品备注')
    goods_attr = models.IntegerField(null=True, blank=True, verbose_name='商品属性ID')
    goods_unit = models.IntegerField(null=True, blank=True, verbose_name='商品单位ID')
    stores_id = models.IntegerField(null=True, blank=True, verbose_name='仓库ID')
    allow_stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='可用库存')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='基本单位ID')
    basic_nmber = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='基本数量')
    unit_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='购货单价')
    tax_included = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                       validators=[MinValueValidator(0)], verbose_name='含税单价')
    discount = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='折扣率(%)')
    dis_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='折扣额')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    tax_rate = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                   validators=[MinValueValidator(0)], verbose_name='税率(%)')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                    validators=[MinValueValidator(0)], verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                          validators=[MinValueValidator(0)], verbose_name='价税合计')
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货订单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    preferential_rate = models.FloatField(default=0.00, validators=[MinValueValidator(0)], verbose_name='优惠率(%)')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='付款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户ID')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    order_info_id = models.CharField(max_length=255, null=True, blank=True, verbose_name='购货订单详情ID')
    batch_id = models.IntegerField(null=True, blank=True, verbose_name='批次ID')
    batch_name = models.CharField(max_length=100, null=True, blank=True, verbose_name='批次名称')
    manufacture = models.IntegerField(null=True, blank=True, verbose_name='生产日期')
    guarantee = models.IntegerField(null=True, blank=True, verbose_name='保质期(天)')
    validity = models.IntegerField(null=True, blank=True, verbose_name='有效期至')
    period = models.TextField(null=True, blank=True, verbose_name='序列号')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_goods_purchase_info'
        verbose_name = '商品采购明细'
        verbose_name_plural = '商品采购明细'

    def save(self, *args, **kwargs):
        # 计算保质期时间
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400

        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.purchase_code or '无编号'}-{self.goods_code}"


# 采购单关联表
class FaKuyouGoodsPurOrd(models.Model):
    """
    采购订单关联表
    用于关联采购订单与其他业务单据
    """
    id = models.AutoField(primary_key=True, verbose_name='主键ID')
    order_id = models.IntegerField(default=0, verbose_name='关联订单ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='采购单ID')

    class Meta:
        db_table = 'fa_kuyou_goods_purord'
        verbose_name = '采购订单关联'
        verbose_name_plural = '采购订单关联'

    def __str__(self):
        return f"关联ID:{self.id} (订单:{self.order_id}→采购单:{self.purchase_id})"


# 采购详情单关联表
class FaKuyouGoodsPurOrdInfo(models.Model):
    TYPE_CHOICES = [
        ('0', '未定义'),
        ('1', '购货订单'),
        ('2', '购货单'),
    ]

    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='主键ID')
    order_id = models.IntegerField(default=0, verbose_name='关联订单ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='购货明细ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        null=True,
        default=None,
        verbose_name='关联类型'
    )
    number = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='数量',
        null=True
    )
    money = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        null=True,
        verbose_name='已付款金额'
    )
    all_money = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        null=True,
        verbose_name='购货金额'
    )
    tax_rate = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='税率(%)'
    )
    tax_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='税额'
    )
    money_tax_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='价税合计'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        null=True,
        verbose_name='状态'
    )
    times = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作次数'
    )

    class Meta:
        db_table = 'fa_kuyou_goods_purord_info'
        verbose_name = '采购订单关联详情'
        verbose_name_plural = '采购订单关联详情'
        indexes = [
            models.Index(fields=['order_id', 'purchase_id']),
        ]

    def save(self, *args, **kwargs):
        """自动计算金额字段"""
        # 计算税额
        if not self.tax_money and self.all_money and self.tax_rate:
            self.tax_money = float(self.all_money) * float(self.tax_rate) / 100

        # 计算价税合计
        if not self.money_tax_price and self.all_money:
            self.money_tax_price = float(self.all_money) + float(self.tax_money or 0)

        super().save(*args, **kwargs)


# 购货退货单
class FaKuyouGoodsExchange(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('0', '退货单'),
        ('1', '购货订单退货'),
        ('2', '购货单退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未付款'),
        ('1', '全部付款'),
        ('2', '部分付款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    RETREAT_STATUS_CHOICES = [
        ('0', '未退款'),
        ('1', '全部退款'),
        ('2', '部分退款'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, default='2', verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    supplyer_code = models.CharField(max_length=30, null=True, blank=True, verbose_name='供应商编号')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货订单号')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    preferential_rate = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                            validators=[MinValueValidator(0)], verbose_name='优惠率')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='税额')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人')
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='付款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户')
    retreat_status = models.CharField(max_length=1, choices=RETREAT_STATUS_CHOICES, null=True, blank=True,
                                      verbose_name='退款状态')
    retreat_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='退货数量')
    retreat_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                        validators=[MinValueValidator(0)], verbose_name='退款金额')
    note = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                  verbose_name='本次欠款')
    all_arrears = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='总欠款')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    cost_data = models.TextField(null=True, blank=True, verbose_name='采购销售费用')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=time.time())
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=time.time())

    class Meta:
        db_table = 'fa_kuyou_goods_exchange'
        verbose_name = '购货退货单'
        verbose_name_plural = '购货退货单'

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - {self.get_purchase_type_display()}"

    def save(self, *args, **kwargs):
        self.purchase_time = int(time.time())
        self.pay_money = 0
        self.account = 0
        if self.retreat_money < self.real_money:
            self.retreat_status = '2'
        elif self.pay_money == self.real_money:
            self.retreat_status = '1'
        else:
            self.retreat_status = '0'

        # 计算欠款
        self.arrears = float(self.real_money) - float(self.retreat_money)
        # 更新总欠款（供应商表中记录）
        supplier = FaKuyouSuppliers.objects.filter(supplyer_code=self.supplyer_code).first()
        self.all_arrears = supplier.need_give_account + supplier.receive_account - float(self.arrears)
        supplier.save()


        super().save(*args, **kwargs)


# 购货退货详情单
class FaKuyouGoodsExchangeInfo(models.Model):
    PURCHASE_TYPE_CHOICES = [
        ('0', '未知类型'),  # 原表注释中未定义0，但保留兼容
        ('1', '购货'),
        ('2', '退货'),
    ]

    PAY_STATUS_CHOICES = [
        ('0', '未付款'),
        ('1', '部分付款'),
        ('2', '全部付款'),
    ]

    CHECK_STATUS_CHOICES = [
        ('0', '未对单'),
        ('1', '已对单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    RETREAT_STATUS_CHOICES = [
        (0, '未退款'),
        (1, '全部退款'),
        (2, '部分退款'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_type = models.CharField(max_length=1, choices=PURCHASE_TYPE_CHOICES, null=True, blank=True,
                                     verbose_name='类型')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据日期', default=time.time())
    delivery_time = models.IntegerField(null=True, blank=True, verbose_name='交货时间')
    supplyer_code = models.CharField(max_length=30, null=True, blank=True, verbose_name='供应商编号')
    goods_code = models.CharField(max_length=30, default='', verbose_name='商品编号')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品备注')
    goods_attr = models.IntegerField(null=True, blank=True, verbose_name='商品属性')
    goods_unit = models.IntegerField(null=True, blank=True, verbose_name='商品单位')
    stores_id = models.IntegerField(null=True, blank=True, verbose_name='仓库')
    allow_stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='可用库存')
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                 verbose_name='数量')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='基本单位')
    basic_nmber = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                      validators=[MinValueValidator(0)], verbose_name='基本数量')
    unit_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='购货单价')
    tax_included = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='含税单价')
    discount = models.FloatField(default=0.00, verbose_name='折扣率')
    dis_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='折扣额')
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='购货金额')
    tax_rate = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='税率')
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='税额')
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                          verbose_name='价税合计')
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    purchase_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货订单号')
    purchase_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='购货单号')
    sales_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='销货订单号')
    returns_order_id = models.CharField(max_length=50, null=True, blank=True, verbose_name='退货订单号')
    purchase_info_id = models.IntegerField(null=True, blank=True, verbose_name='购货单详情ID')
    preferential_rate = models.FloatField(default=0.00, verbose_name='优惠率')
    preferential_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                             validators=[MinValueValidator(0)], verbose_name='优惠额')
    real_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                     verbose_name='优惠后金额')
    purchase_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='采购费用')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人')
    pay_status = models.CharField(max_length=1, choices=PAY_STATUS_CHOICES, default='0', verbose_name='付款状态')
    check_status = models.CharField(max_length=1, choices=CHECK_STATUS_CHOICES, default='0', verbose_name='对单状态')
    examine_status = models.CharField(max_length=1, choices=EXAMINE_STATUS_CHOICES, default='0',
                                      verbose_name='审核状态')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    pay_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    verbose_name='已付款金额')
    retreat_status = models.SmallIntegerField(choices=RETREAT_STATUS_CHOICES, default=0, verbose_name='退款状态')
    retreat_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                         validators=[MinValueValidator(0)], verbose_name='退货数量')
    retreat_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                        validators=[MinValueValidator(0)], verbose_name='退款金额')
    account = models.IntegerField(null=True, blank=True, verbose_name='付款账户')
    print_num = models.IntegerField(default=0, verbose_name='打印次数')
    batch_id = models.IntegerField(null=True, blank=True, verbose_name='批次ID')
    batch_name = models.CharField(max_length=100, null=True, blank=True, verbose_name='批次名称')
    manufacture = models.IntegerField(null=True, blank=True, verbose_name='生产日期')
    guarantee = models.IntegerField(null=True, blank=True, verbose_name='保质期')
    validity = models.IntegerField(null=True, blank=True, verbose_name='有效期')
    period = models.TextField(null=True, blank=True, verbose_name='序列号')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=time.time())
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=time.time())

    class Meta:
        db_table = 'fa_kuyou_goods_exchange_info'
        verbose_name = '退货明细'
        verbose_name_plural = '退货明细'

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - {self.goods_code}"


# 退货关联表
class FaKuyouGoodsExcpur(models.Model):
    TYPE_CHOICES = [
        ('0', '默认类型'),  # 根据业务需求补充注释
        ('1', '类型1'),  # 原表注释未明确具体含义
        ('2', '类型2'),
    ]

    id = models.AutoField(primary_key=True)
    exchange_id = models.IntegerField(default=0, verbose_name='退单ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='购货单ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='0',
        verbose_name='单据类型'
    )

    class Meta:
        db_table = 'fa_kuyou_goods_excpur'
        verbose_name = '退单关联'
        verbose_name_plural = '退单关联'
        # 建议添加联合索引（根据实际查询需求）
        indexes = [
            models.Index(fields=['exchange_id', 'purchase_id']),
        ]

    def __str__(self):
        return f"退单关联 {self.id} (类型:{self.get_type_display()})"


# 退货关联详情表
class FaKuyouGoodsExcpurInfo(models.Model):
    TYPE_CHOICES = [
        ('0', '未知类型'),
        ('1', '购货订单'),
        ('2', '购货单'),
    ]

    STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    exchange_id = models.IntegerField(default=0, verbose_name='退单ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='购货单ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='类型'
    )
    number = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='数量'
    )
    money = models.FloatField(
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='退款金额'
    )
    all_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='购货金额'
    )
    tax_rate = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='税率'
    )
    tax_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='税额'
    )
    money_tax_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='价税合计'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    times = models.IntegerField(null=True, blank=True, verbose_name='次数', default=int(time.time()))

    class Meta:
        db_table = 'fa_kuyou_goods_excpur_info'
        verbose_name = '退单关联明细'
        verbose_name_plural = '退单关联明细'
        indexes = [
            models.Index(fields=['exchange_id', 'purchase_id']),
        ]

    def __str__(self):
        return f"退单明细 {self.id} (类型:{self.get_type_display()})"
